﻿namespace System.Data.Entity.ModelConfiguration.Conventions
{
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Infrastructure.Annotations;
    using System.Data.Entity.Utilities;
    using System.Linq;

    public class FullTextSearchConvention : IStoreModelConvention<EntityContainer>
    {
        public void Apply(EntityContainer item, DbModel model)
        {
            if (model == null)
                return;

            foreach (var storeEntity in model.StoreModel.EntityTypes)
            {
                var property = storeEntity.MetadataProperties.SingleOrDefault(metadataproperty =>
                    metadataproperty.Name == XmlConstants.FullTextIndexedTableAnnotationWithPrefix);

                if (property == null)
                    continue;

                FullTextIndexedTableAnnotation annotation = (FullTextIndexedTableAnnotation)property.Value;

                var entity = model.ConceptualToStoreMapping.EntitySetMappings.Single(set =>
                    set.EntityTypeMappings.Any(map => map.Fragments.Single().StoreEntitySet.ElementType == storeEntity))
                    .EntitySet.ElementType;

                var function = model.CreateFunctionDescriptor(
                    string.Concat(annotation.FullTextIndexedTable.Prefix, entity.Name),
                    entity
                    );
            }
        }
    }
}